<?php
/**
 * 订单模块
 * 2019.3.13
 * 吴
 */
namespace app\api\controller;

use think\Db;
use think\Request;
use app\api\service\OrderService;

class OrderController extends BaseController{


	/**
	 * 购物车接口
	 */
	public function car_index(){
        $this->checkUser();
	    $user_id = $this->user_id;
	    $goodsList = Db::name('cart')->alias('c')
                   ->field('c.*,g.goods_title,g.goods_price,g.goods_thumb')
                   ->join('goods g','g.goods_id = c.goods_id')
                   ->where('c.user_id',$user_id)->select();
	    $req = request();
	    $domain = $req->domain();
        $lists = $goodsList->all();
        foreach ($lists as $k=>$item) {
            $lists[$k]['goods_thumb'] = $domain.$item['goods_thumb'];
            $lists[$k]['goods_total_price'] = number_format($item['goods_price'] * $item['nums'],2,'.','');
	    }
        $this->ApiResult(true,10000,'操作成功',$lists);
	}

    /**
     * 加入购物车|修改购物车
     * @param type 1=加1,2=减，默认为1
     */
	function addToCart(){
        $this->checkUser();
        $type = input('type');
        $type = $type ? $type : 1;
        $goods_id = 1;   //单商品，商品ID默认为1
        $record = Db::name('cart')->where('user_id = "'.$this->user_id.'" and goods_id = "'.$goods_id.'"')->find();
        if($record){
            if($type == 1){
                Db::name('cart')->where('user_id = "'.$this->user_id.'" and goods_id = "'.$goods_id.'"')->setInc('nums');
            }else{
                Db::name('cart')->where('user_id = "'.$this->user_id.'" and goods_id = "'.$goods_id.'"')->setDec('nums');
            }
        }else{
            $record = array('user_id'=>$this->user_id,'goods_id'=>$goods_id,'nums'=>1);
            Db::name('cart')->insert($record);
        }
        $this->ApiResult(true,10000,'操作成功');
    }



    /**
     * 创建订单
     *
     * @param goods_id = 商品ID 必填
     * @param number = 商品数量 必填
     * @param addr_id = 收货地址ID 必填
     * @param payment_type = 支付类型：1=余额支付，2=微信支付，3=支付宝支付 必填
     * @param cart_id = 购物车ID 必填
     */
    public function createOrder(){
        $this->checkUser();
        $goods_id = $this->request->post('goods_id','');
        $number = $this->request->post('number','');
        $addr_id = $this->request->post('addr_id','');
        $payment_type = $this->request->post('payment_type','');
        $cart_id = $this->request->post('cart_id','');
        if(empty($goods_id)||empty($number)||empty($addr_id)||empty($payment_type)){
            $this->ApiResult(false,10001,'参数不能为空');
        }
        $addr_info = Db::name('user_express_address')->where('id = '.$addr_id.' AND user_id = '.$this->user_id)->find();
        if(empty($addr_info)){
            $this->ApiResult(false,10001,'请选择收货地址');
        }
        $stock = Db::name('goods')->field('goods_stock')->where('goods_id',$goods_id)->find();
        if($stock < $number){
            $this->ApiResult(false,10001,'商品库存不足');
        }
        $order = new OrderService();
        //加入订单
        $res = $order->createOrder($goods_id,$number,$addr_info,$payment_type,$this->user);
        if($res['order_id']){
           Db::name('cart')->where('car_id',$cart_id)->delete();
           $this->ApiResult(true,10000,'创建订单成功',$res);
        }else{
           $this->ApiResult(false,10001,'提交订单信息有误');
        }
    }



    /**
     * 订单支付
     *
     * @param out_trade_no = 外部交易号 必填
     * @param payment_type = 支付类型 必填
     * @param pay_code = 支付密码 必填
     */
    public function orderPayment(){
        $this->checkUser();
        $out_trade_no = $this->request->post('out_trade_no','');
        $payment_type = $this->request->post('payment_type','');
        $pay_code     = $this->request->post('pay_code',''); 
        if(empty($this->user['pay_code'])){
            $this->ApiResult(false,10001,'支付密码未设置');
        }
        if(!password_verify($pay_code, $this->user['pay_code'])) {
            $this->ApiResult(false,10001,'支付密码错误');
        }
        $order = new OrderService();
        $res = $order->orderPayment($out_trade_no,$payment_type,$pay_code,$this->user);
        if($res['code'] != 10000){
            $this->ApiResult(false,10001,$res['msg']);
        }
        $this->ApiResult(true,10000,$res['msg']);
    }



    /**
     * 获取订单
     * 
     * @param order_status 订单状态
     */
    public function getOrder(){
        $this->checkUser();
        $order_status = $this->request->request('order_status','');
        $page = input('page/d')?input('page/d'):1;
        $size = input('size/d')?input('size/d'):10;    
        $where = 'user_id = '.$this->user_id;
        if($order_status == ''){
            $this->ApiResult(false,10001,'请求参数不能为空');
        }
        $arr = '';
        if($order_status == 1){
           $where .= ' AND order_status = 0';
        }else if($order_status == 2){
           $where .= ' AND order_status = 1';
        }else if($order_status == 3){
           $where .= ' AND order_status = 2';
        }else if($order_status == 4){
           $arr = '5,6,7,8,9,10,11,12';
        }
        if(empty($arr)){
            $data = Db::name('order')->where($where)->limit(($page-1)*$size, $size)->order('order_id desc')->select()->toarray();
        }else{
            $data = Db::name('order')->where($where)->where('order_status','in',$arr)->limit(($page-1)*$size, $size)->order('order_id desc')->select()->toarray();
        }
        //暂时这样用
        foreach ($data as $k => $v) {
            $data[$k]['goods_thumb'] = 'http://47.107.243.64:8001'.$v['goods_thumb'];
        }
        $total = Db::name('order')->where($where)->count();
        $this->ApiResult(true,10000,'获取成功',['total'=>$total,'data'=>$data]);
    }



    /**
     * 收货、退货、换货
     *
     * @param type 1=收货，2=退货，3=换货
     */
    public function orderEditStatus(){
        $this->checkUser();
        $out_trade_no = $this->request->post('out_trade_no');
        $type = $this->request->post('type');
        if(empty($out_trade_no) || empty($type)){
            $this->ApiResult(false,10001,'请求参数不能为空');
        }
        $data = Db::name('order')
              ->where('user_id',$this->user_id)
              ->where('out_trade_no',$out_trade_no)
              ->find();
        if($type == 1 && $data['order_status'] != 2){
            $this->ApiResult(false,10001,'该订单不需要收货');
        }
        if($type == 2 && $data['order_status'] != 3){
            $this->ApiResult(false,10001,'该订单不可以退货');
        }
        if($type == 3 && $data['order_status'] != 3){
            $this->ApiResult(false,10001,'该订单不可以换货');
        }
        if($type == 2 || $type == 3){
            $time = (time() - strtotime($data['sign_time']))/86400;
            if($time > 7){
                $this->ApiResult(false,10001,'该订单收货时间已超过7天，不支持退货换货功能');
            }
        }
        if($type == 1){
            $order_info = [
               'order_status' => 3,
               'sign_time'    => date('Y-m-d H:i:s',time()),
            ];
        }else if($type == 2 || $type == 3){
            if($type == 2){
                $status = 7;
            }else{
                $status = 8;
            }
            $order_info = [
               'order_status' => $status,
            ];
        }else{
            $order_info = [];
        }
        $res = Db::name('order')->where('out_trade_no',$out_trade_no)->update($order_info);
        if($res){
            $this->ApiResult(true,10000,'成功');
        }else{
            $this->ApiResult(false,10001,'失败');
        }
    }




    /**
     * 查看物流
     *
     * @param out_trade_no 订单号
     * @param type 类型 1=查看后台发货物流，2=查看前台添加的物流，3=后台换货的物流 
     */
    public function lookLogistics(){
        $this->checkUser();
        $out_trade_no = $this->request->post('out_trade_no');
        $type = $this->request->post('type');
        $data = Db::name('order')
              ->alias('a')
              ->field('a.out_trade_no,b.*')
              ->join('order_express b','a.order_id=b.order_id','left')
              ->where('a.out_trade_no',$out_trade_no)
              ->where('b.type',$type)
              ->find();
        $order = new OrderService();
        $res = $order->express($data['express_no']);
        $info = json_decode($res,true);
        if($info['message'] == 'ok'){
            $this->ApiResult(true,10000,'成功',$info);
        }else{
            $this->ApiResult(false,10001,'没有物流信息');
        }
    }



    /**
     * 退货添加物流信息
     *
     * @param out_trade_no 外部交易号
     * @param express_company 物流公司名称
     * @param express_no 物流单号
     */
    public function retreatAddLogistics(){
        $this->checkUser();
        $out_trade_no = $this->request->post('out_trade_no');
        $express_no = $this->request->post('express_no');
        $express_company = $this->request->post('express_company');
        if(empty($out_trade_no) || empty($express_no) || empty($express_company)){
            $this->ApiResult(false,10001,'请求参数不能为空');
        }
        $order_info = Db::name('order')->where('out_trade_no',$out_trade_no)->find();
        //前端无法判断该订单是否提交过物流，暂时这样处理
        $is_express = Db::name('order_express')->where('order_id = "'.$order_info['order_id'].'" and type = 2')->find();
        if($is_express){
            $this->ApiResult(false,10001,'您已提交过物流信息，请勿重复提交');
        }
        // if($order_info['order_status'] !== 9 || $order_info['order_status'] !== 10){
        //     $this->ApiResult(false,10001,'该订单不处于退货或者换货状态，不可添加物流');
        // }
        $data_info = [
          'order_id'        => $order_info['order_id'],
          'goods_id'        => $order_info['goods_id'],
          'express_company' => $express_company,
          'express_no'      => $express_no,
          'user_id'         => $order_info['user_id'],
          'user_name'       => $order_info['user_name'],
          'shipping_time'   => date('Y-m-d H:i:s',time()),
          'status'          => 0,
          'type'            => 2
        ];
        $res = Db::name('order_express')->insert($data_info);
        if($res){
            $this->ApiResult(true,10000,'添加成功');
        }else{
            $this->ApiResult(false,10001,'添加失败');
        }
    }




    /**
     * 确定收款
     */
    public function proceeds(){
        $this->checkUser();
        $out_trade_no = $this->request->post('out_trade_no');
        $order_info = Db::name('order')->where('out_trade_no',$out_trade_no)->find();
        if($order_info['order_status'] !== 5){
            $this->ApiResult(false,10001,'该订单不可收款');
        }
        $data = [
           'balance'   => $this->user['balance'] + $order_info['order_money'],
        ];
        $order = Db::name('order')
               ->where('out_trade_no',$out_trade_no)
               ->update(['order_status'=>6,'refund_money'=>$order_info['order_money']]);
        if(empty($order)){
            $this->ApiResult(false,10001,'退款失败');
        }
        //扣款
        Db::startTrans(); //启动事务
        try {
            $res = Db::name('shop_user')
                 ->where('user_id',$this->user['user_id'])
                 ->update($data);
            Db::commit(); //提交事务
        } catch (\PDOException $e) {
            Db::rollback(); //回滚事务
        }
        //添加记录
        $balance_info = [
           'money'       => $order_info['order_money'],
           'scene'       => 3,
           'sign'        => 1,
           'create_time' => date('Y-m-d H:i:s',time()),
           'user_id'     => $this->user_id,
           'remarks'     => '退款添加的余额',
           'data_id'     => $order_info['order_id']
        ];
        Db::name('balance_record')->insert($balance_info);
        if($res){
           $this->ApiResult(true,10000,'退款成功');
        }else{
           $this->ApiResult(false,10001,'退款失败');
        }
    }



    /**
     * 确认订单已完成
     */
    public function completeOrder(){
        $this->checkUser();
        $out_trade_no = $this->request->post('out_trade_no');
        $order_info = Db::name('order')->where('out_trade_no',$out_trade_no)->find();
        if($order_info['order_status'] == 3 || $order_info['order_status'] == 11 || $order_info['order_status'] == 12){
            $order = new OrderService();
            $res = $order->completeOrder($order_info,$this->user);
            if($res['code'] != 10000){
                $this->ApiResult(false,10001,$res['msg']);
            }
            $this->ApiResult(true,10000,$res['msg']);
        }else{
            $this->ApiResult(false,10001,'该订单不可完成');
        }
    }



    /**
     * 定时执行完成订单
     * 
     * @param type = 1
     * 自收货时间开始计算，7天自动订单完成
     *  
     * @param type = 2
     * 15天自动收货，同时订单已完成，不可进行退货退款，换货等
     */
    public function timingComplete(){
        $type = $this->request->post('type');
        if($type == 1){
            $time = date('Y-m-d H:i:s',strtotime('-7 days'));
            $data = Db::name('order')
                  ->where('order_status','in','3,11,12')
                  ->where("sign_time < '".$time."'")
                  ->select()
                  ->toarray();
        }else if($type == 2){
            $time = date('Y-m-d H:i:s',strtotime('-15 days'));
            $data = Db::name('order')
                  ->where('order_status','2')
                  ->where("shipping_time < '".$time."'")
                  ->select()
                  ->toarray();
        }else{
            $this->ApiResult(false,10001,'参数错误');
        }
        if(empty($data)){
            $this->ApiResult(true,10000,'成功');
        }
        $user_ids = array();
        foreach ($data as $k => $v) {
            $user_ids[] = $v['user_id'];
        }
        $order = new OrderService();
        $user_ids = implode(',', array_unique($user_ids));
        $user_info = Db::name('shop_user')->where('user_id','in',$user_ids)->select()->toarray();
        foreach ($data as $key => $value) {
            foreach ($user_info as $k => $v) {
                if($value['user_id'] == $v['user_id']){
                    $res = $order->completeOrder($data[$key],$user_info[$k],1);
                    if($res['code'] == -1){
                        $this->ApiResult(false,10001,$res['msg']);
                    }
                }
            }
        }
        $this->ApiResult(true,10000,'成功');
    }



    
    /**
     * 从银遇过来的用户信息
     */
    public function createUser(){
        $data = $this->request->post();
        if(empty($data)){
            $this->ApiResult(false,10001,'参数错误');
        }
        $user = Db::name('shop_user')->where('mobile',$data['user_tel'])->find();
        if(empty($user)){
            $user_info = [
               'user_name'      => $data['user_tel'],
               'mobile'         => $data['user_tel'],
               'password'       => password_hash('123456',PASSWORD_DEFAULT),
               'nick_name'      => $data['user_tel'],
               'create_time'    => time(),
               'volume'         => $data['number'],
               'oneself_volume' => $data['number'],
               'is_source'      => 1,
            ];
            $res = Db::name('shop_user')->insert($user_info);
            if($res){
               $this->ApiResult(true,10000,'成功');
            }else{
               $this->ApiResult(false,10001,'失败');
            }
        }else{
            $user_info = [
               'volume'         => $user['volume']+$data['number'],
               'oneself_volume' => $user['oneself_volume']+$data['number'],
            ];
            $res = Db::name('shop_user')->where('mobile',$data['user_tel'])->update($user_info);
            if($res){
               $this->ApiResult(true,10000,'成功');
            }else{
               $this->ApiResult(false,10001,'失败');
            }
        }
    }


 

}